<template>
  <t-dialog :visible="visible" attach="#app" header="设置班级" :confirm-btn="{ content: '设置' }" @confirm="submit" @close="closeDialog">
    <t-form :rules="formRules" :data="form">
      <t-form-item label="班级" name="class_id">
        <t-select v-model="form.class_id" class="demo-select-base">
          <t-option v-for="(item, index) in classOptions" :key="index" :value="item.value" :label="item.label">
            {{ item.label }}
          </t-option>
        </t-select>
      </t-form-item>
    </t-form>
  </t-dialog>
</template>
<script setup lang="ts">
import {onMounted, ref} from "vue";
import {queryClass} from "../api/Class";
import { addStudent } from "../api/Student";
import {MessagePlugin} from "tdesign-vue-next";

// 表单数据
interface formType {
  user_id: number | string;
  class_id: number | string;
}
const form = ref<formType>({
  user_id: '',
  class_id: ''
})
interface classOptionsType {
  label: string;
  value: number;
}
const classOptions = ref<Array<classOptionsType>>([]);
const visible = ref<boolean>(false);
// 表单校验规则
const formRules = ref({
  class_id: [{ required: true, message: '请选择班级' }],
});
const open = (user_id:number) => {
  visible.value = true;
  form.value.user_id = user_id;
}
const submit = async () => {
  const result = await addStudent(form.value);
  if(result){
    MessagePlugin.success(result.message);
    visible.value = false;
  }
}
const closeDialog = () => {
  visible.value = false;
}
// 请求班级列表API
const queryClassType = async ():Promise<void> => {
  const classTypes = await queryClass();
  interface dataType {
    classname: string;
    id: number;
    create_time: string;
    update_time: string;
  }
  if(classTypes) {
    classTypes.data.forEach((item:dataType, i) => {
      classOptions.value.push({
        label: item.classname,
        value: item.id
      })
    });
  }
}
onMounted(()=>{
  queryClassType();
})
defineExpose({open})
</script>
<style lang="less"></style>
